package com.ruoyi.framework.storage;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.core.io.Resource;

import java.io.InputStream;
import java.nio.file.Path;

/**
 * 提供存储服务类，所有存储服务均由该类对外提供
 */
@RequiredArgsConstructor
public class StorageService {
    private final Storage storage;

    /**
     * 存储一个文件对象
     *
     * @param inputStream   文件输入流
     * @param fileName      文件索引名
     */
    public String store(InputStream inputStream, String fileName, String contentType) {
        String key = generateKey(fileName);
        return storage.store(inputStream, key, contentType);
    }

    private String generateKey(String originalFilename) {
        String suffix = FileUtil.getSuffix(originalFilename);
        return RandomUtil.randomString(20) + "." + suffix;
    }

    public Path load(String keyName) {
        return storage.load(keyName);
    }

    public Resource loadAsResource(String keyName) {
        return storage.loadAsResource(keyName);
    }

    public void delete(String keyName) {
        storage.delete(keyName);
    }

    public String generateUrl(String keyName) {
        return storage.generateUrl(keyName);
    }
}
